;
$(function () {
    var prompt = $('.pop_window1');
    var $list = $('#list');
    let addressData = null
    let isMember = 1 // 用户是否为会员，1为初始化数据，表示请求异常或请求还未返回
    //请求地址参数
    new ajax({
        url: 'user/address/getUserAddr.do',
        type: 'post',
        dataType: 'json',
        contentType: 'application/json;charset=utf-8',
        data: JSON.stringify({}),
        success: function ({data, respCode}) {
            if (respCode != "S") {
                $list.empty();
                prompt.children().html("您暂无收货地址").end().show(function () {
                    const this_ = $(this);
                    setTimeout(function () {
                        this_.hide();
                    }, 1000);
                });
                return;
            } else {
                if (data.receiveAddressList.length === 0) {
                    $list.empty();
                    prompt.children().html("您暂无收货地址").end().show(function () {
                        const this_ = $(this);
                        setTimeout(function () {
                            this_.hide();
                        }, 1000);
                    });
                    isMember = data.isMember
                    addressData = data.receiveAddressList
                    return;
                } else {
                    isMember = data.isMember
                    addressData = data.receiveAddressList
                }
            }

            //再次请求拿默认地址
            new ajax({
                url: 'user/address/getDefaultReceiveAddress.do',
                type: 'post',
                dataType: 'json',
                contentType: 'application/json;charset=utf-8',
                data: JSON.stringify({}),
                success: function (obj) {
                    if (obj.respCode != "S") {
                        for (var i = 0; i < addressData.length; i++) {
                            var $li = $(` <div class="delivery_add">
                            <div class="delivery_name"><span>${addressData[i].receiverName}（${addressData[i].sex === 'MALE' ? '先生' : '女士'}）</span>${addressData[i].mobile}</div>
                            <div class="delivery_address">${addressData[i].areaName}${addressData[i].smallName}${addressData[i].addressTwo}</div>
                            <div class="delivery_state"><input data-index="${i+1}" type="radio" name="default" id="default${i}" ><label for="default${i}">设为默认</label><button>删除</button><em style="display:none">${addressData[i].receiveAddressId}</em></div>
                            </div>`);
                            $li.appendTo($list);
                            $list.attr('data-index',0)
                        }
                    } else {
                        for (var i = 0; i < addressData.length; i++) {
                            if (obj.data.receiveAddressId == addressData[i].receiveAddressId) {
                                var $li = $(` <div class="delivery_add">
                                <div class="delivery_name"><span>${addressData[i].receiverName}（${addressData[i].sex === 'MALE' ? '先生' : '女士'}）</span>${addressData[i].mobile}</div>
                                <div class="delivery_address">${addressData[i].areaName}${addressData[i].smallName}${addressData[i].addressTwo}</div>
                                <div class="delivery_state"><input data-index="${0}" type="radio" name="default" id="default${i}" checked="checked"><label for="default${i}">设为默认</label><button>删除</button><em style="display:none">${addressData[i].receiveAddressId}</em></div>
                                </div>`);
                                $li.prependTo($list); //放到子节点前面
                            } else {
                                var $li = $(` <div class="delivery_add">
                                <div class="delivery_name"><span>${addressData[i].receiverName}（${addressData[i].sex === 'MALE' ? '先生' : '女士'}）</span>${addressData[i].mobile}</div>
                                <div class="delivery_address">${addressData[i].areaName}${addressData[i].smallName}${addressData[i].addressTwo}</div>
                                <div class="delivery_state"><input data-index="${i+1}" type="radio" name="default" id="default${i}" ><label for="default${i}">设为默认</label><button>删除</button><em style="display:none">${addressData[i].receiveAddressId}</em></div>
                                </div>`);
                                $li.appendTo($list);
                            }
                            $list.attr('data-index',0)
                        }
                    }
                },
                error: function () {
                    prompt.children().html("网络出错").end().show(function () {
                        const this_ = $(this);
                        setTimeout(function () {
                            this_.hide();
                        }, 900);
                    });
                }
            })


        },
        error: function () {
            prompt.children().html("请求地址出错").end().show(function () {
                const this_ = $(this);
                setTimeout(function () {
                    this_.hide();
                }, 900);
            })
        }
    })

    function message (key){
        prompt.children().html(key).end().show(function () {
            const self = $(this);
            setTimeout(function () {
                self.hide();
            }, 1000);
        });
    }

    //设为默认
    $list.delegate('input', 'click', function () {
        var id = $(this).next().next().next().text();
        const that = $(this);
        console.log(that.attr('data-index'))
        if(that.attr('data-index') == $('#list').attr('data-index')){
            message('默认地址不可取消哦~')
        }else{
            new ajax({
                url: 'user/address/accGoodsAddrDef.do',
                type: 'post',
                dataType: 'json',
                contentType: 'application/json;charset=utf-8',
                data: JSON.stringify({
                    "receiveAddressId": id
                }),
                success:function ({
                                      respCode
                                  }) {
                    if (respCode == "S") {
                        $('#list').attr('data-index',that.attr('data-index'))
                        message('修改成功')
                    }
                },
                error:function () {
                    console.log("error");
                }
            })
        }
    });

    //删除地址
    $list.delegate('button', 'click', function () {
        var id = Number($(this).next().text());
        let addressId = addressData.map(item => {
            return item.receiveAddressId
        })
        let index = addressId.indexOf(id)
        
        const this_ = $(this);
        new ajax({
            url: 'user/address/deleteGoodsAddrDef.do',
            type: 'post',
            dataType: 'json',
            contentType: 'application/json;charset=utf-8',
            data: JSON.stringify({
                "receiveAddressId": id,
            }),
            success:function ({
                                  respCode
                              }) {
                if (respCode == "S") {
                    this_.parent().parent().remove();
                    addressData.splice(index, 1)
                } else {
                    prompt.children().html("删除失败").end().show(function () {
                        const this_ = $(this);
                        setTimeout(function () {
                            this_.hide();
                        }, 600);
                    });
                }

            },
            error:function () {
                prompt.children().html("网络出错").end().show(function () {
                    const this_ = $(this);
                    setTimeout(function () {
                        this_.hide();
                    }, 800);
                });
            }
        })

    });


    //新增地址
    $(".new_add").click(function () {
        if (isMember) {
            if (isMember === 1) {
                message('网络异常，请稍后再试')
            } else {
                if (addressData.length === 2) {
                    message('会员最多只能添加两个收货地址！')
                } else if (addressData.length < 2) {
                    window.location.href = "my_addshouhuo.html";
                }
            }
        } else {
            if (addressData.length !== 0) {
                message('普通用户最多只能添加一个收货地址！')
            } else {
                window.location.href = "my_addshouhuo.html";
            }
        }
    });


    //返回
    $(".member_fanhui").click(function () {
        if (document.referrer.indexOf("addshouhuo") != -1) {
            window.location.href = "../my/my.html"
        } else {
            window.history.go(-1)
        }
    });
});
